// vite.config.ts
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { fileURLToPath, URL } from 'node:url'
import { getFullConfig, API_PREFIXES } from './src/request/config' // 导入 getFullConfig 函数

export default defineConfig(({ mode }: { mode: string }) => {
  // 根据传入的 mode 获取正确的配置（在 Node.js 环境中，import.meta.env 不可用）
  const currentConfig = getFullConfig(mode)
  
  // 验证 apiService 的 pathRewrite 配置
  console.log('========================================')
  console.log('📋 Vite 代理配置验证')
  console.log('========================================')
  console.log('当前环境:', mode || 'development')
  console.log('')
  console.log('🔵 apiService 配置:')
  console.log('  URL:', currentConfig.apiService.url)
  console.log('  pathRewrite:', currentConfig.apiService.pathRewrite || '未配置（保留完整路径）')
  if (currentConfig.apiService.pathRewrite) {
    const rules = Object.entries(currentConfig.apiService.pathRewrite)
    rules.forEach(([pattern, replacement]) => {
      console.log(`    - "${pattern}" → "${replacement}"`)
      // 测试示例路径
      const testPath = '/api/login/userinfo'
      const regex = new RegExp(pattern)
      if (regex.test(testPath)) {
        const rewritten = testPath.replace(regex, replacement)
        console.log(`      示例: "${testPath}" → "${rewritten}"`)
      }
    })
  }
  console.log('')
  console.log('🟢 screenService 配置:')
  console.log('  URL:', currentConfig.screenService.url)
  console.log('  pathRewrite:', currentConfig.screenService.pathRewrite || '未配置（保留完整路径）')
  if (currentConfig.screenService.pathRewrite) {
    const rules = Object.entries(currentConfig.screenService.pathRewrite)
    rules.forEach(([pattern, replacement]) => {
      console.log(`    - "${pattern}" → "${replacement}"`)
      // 测试示例路径
      const testPath = '/api/screen/list'
      const regex = new RegExp(pattern)
      if (regex.test(testPath)) {
        const rewritten = testPath.replace(regex, replacement)
        console.log(`      示例: "${testPath}" → "${rewritten}"`)
      }
    })
  }

  return {
    plugins: [vue()],
    server: {
      proxy: {
        // 动态配置 apiService 代理
        // 匹配 /api 开头的请求，转发到 apiService
        [API_PREFIXES.API]: {
          target: currentConfig.apiService.url, // 从配置中心读取
          changeOrigin: true,
          // 去掉 /api 前缀后转发
          // 例如: /api/login/userinfo → /login/userinfo
          rewrite: (path: string) => {
            const originalPath = path
            const rewrittenPath = path.replace(new RegExp(`^${API_PREFIXES.API}`), '')
            const fullUrl = `${currentConfig.apiService.url}${rewrittenPath}`
            
            console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━')
            console.log('🔄 Vite 代理路径重写 (apiService):')
            console.log('  代理前缀:', API_PREFIXES.API)
            console.log('  原始路径:', originalPath)
            console.log('  重写后路径:', rewrittenPath)
            console.log('  目标URL:', fullUrl)
            console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━')
            
            return rewrittenPath
          },
        },
        // 动态配置 screenService 代理
        // 匹配 /screen 开头的请求，转发到 screenService
        [API_PREFIXES.SCREEN]: {
          target: currentConfig.screenService.url, // 从配置中心读取
          changeOrigin: true,
          // 去掉 /screen 前缀后转发
          // 例如: /screen/list → /list
          rewrite: (path: string) => {
            const originalPath = path
            const rewrittenPath = path.replace(new RegExp(`^${API_PREFIXES.SCREEN}`), '')
            const fullUrl = `${currentConfig.screenService.url}${rewrittenPath}`
            
            console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━')
            console.log('🔄 Vite 代理路径重写 (screenService):')
            console.log('  代理前缀:', API_PREFIXES.SCREEN)
            console.log('  原始路径:', originalPath)
            console.log('  重写后路径:', rewrittenPath)
            console.log('  目标URL:', fullUrl)
            console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━')
            
            return rewrittenPath
          },
        }
      }
    },
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url))
      }
    }
  }
})
